package com.h3bpm.starcharge.controller.bpm;

import OThinker.Common.Organization.Interface.IOrganization;
import OThinker.Common.Organization.Models.Unit;
import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


@Controller
@RequestMapping("/Portal/GetStarChargeUser")
public class IOrganizationStarChargeController extends ControllerBase {

    @Override
    public String getFunctionCode() {
        return null;
    }

    /**
     * 获取组织机构列表
     * @param io
     * @param unId
     * @param jsonResult
     * @return
     * @throws Exception
     */
    public JSONObject getUnit(IOrganization io , String unId,JSONObject jsonResult) throws Exception {
        Unit unit =  io.GetUnit(unId);
        jsonResult.getJSONArray("unitStrList").add(unit.getName());
        if(unit.getParentID()!=null){
            getUnit(  io , unit.getParentID(),  jsonResult);
        }
        return jsonResult;
    }

    /**
     * 获取人员信息
     * @param code
     * @return
     */
    @RequestMapping(value = "/getOrganizationUser", produces = "application/json;charset=utf-8")
    @ResponseBody
    public JSONObject getOrganizationUser(String code){
        JSONObject result = new JSONObject();
        result.put("errorNo","0");
        JSONArray arrayUn=new JSONArray();
        result.put("unitStrList" , arrayUn);
        try{
        IOrganization io = getEngine().getOrganization();
          User user = io.GetUserByCode(code);
          if(user.getParentID()!=null) {
              result  = getUnit(io, user.getParentID(), result);
          }
            StringBuffer stringBuffer = null;
          if(result.getJSONArray("unitStrList")!=null){
              stringBuffer=new StringBuffer("");
              arrayUn=result.getJSONArray("unitStrList");
              for(int i=arrayUn.size()-1;i>=0;i--){
                  Object str=arrayUn.get(i);
                  stringBuffer.append(str.toString()+"-");
              }
              if(!"".equals(stringBuffer.toString())) {
                  stringBuffer = new StringBuffer(stringBuffer.substring(0, stringBuffer.length() - 1));
              }
          }
            result.put("userName",user.getName());
            result.put("objectID", user.getObjectID());
          if(stringBuffer!=null) {
              result.put("unitStr", stringBuffer.toString());
          }
        }catch (Exception e){
            result.put("errorNo","1");
            result.put("errorMessage","失败");
           e.printStackTrace();
        }
         return result;
    }

}
